<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/19
 * Time: 17:51
 */

namespace Game\Services;


use Game\Config\Config;
use Game\Lib\G_CONST;
use Game\Lib\Game;
use Game\Lib\Redis_Const;
use Game\Library\Logger;
use Game\Traits\Singleton;


class GameData
{
    use Singleton;

    
    

    /** @var Logger */
    private $logger;

    public function __construct()
    {

    }

   

    

    private function logger(): Logger{
        if (!($this->logger instanceof Logger)) {
            $this->logger = Logger::getInstance();
        }
        return  $this->logger;
    }

    public function writeLog($message, $level = "INFO"){
        $this->logger()->log($message, $level);
    }
    //**************** MYSQL **************************

    

    //**************** LOGIC *********************

    /**
     * 全随机规则
     * @param $player_count
     * @param bool $only_big
     * @return array
     */
    public function dealCard($player_count, $only_big=false){
        $player_cards = array();
        if(!$only_big){
            $Card = array(
                "A2","A3","A4","A5","A6","A7","A8","A9","A10","A11","A12","A13","A14",
                "B2","B3","B4","B5","B6","B7","B8","B9","B10","B11","B12","B13","B14",
                "C2","C3","C4","C5","C6","C7","C8","C9","C10","C11","C12","C13","C14",
                "D2","D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13","D14",
            );
        } else {
            $Card = array(
                "A10","A11","A12","A13","A14",
                "B10","B11","B12","B13","B14",
                "C10","C11","C12","C13","C14",
                "D10","D11","D12","D13","D14",
            );
        }
        mt_srand();
		$indexs = array_rand($Card, 3 * $player_count);
		shuffle($indexs);
		$num = 0;
		for ($i=0; $i < $player_count; $i++) {
			$card_str = $Card[$indexs[$num]].','. $Card[$indexs[$num+1]] .','.$Card[$indexs[$num+2]];
			$player_cards[] = $card_str;
			$num += 3;
			$this->writeLog($card_str);
		}
        return $player_cards;
    }
    public function _cardValue($cards){
        if(count($cards)!=3){
            return 0;
        }
        $suits = array();
        $points= array();
        foreach ($cards as $card) {
            $suits[] = substr($card, 0, 1);
            $points[] = substr($card, 1);
        }

        rsort($points, SORT_NUMERIC);  //大到小排序
        $points_val_str = str_pad($points[0], 2, "0", STR_PAD_LEFT) . str_pad($points[1], 2, "0", STR_PAD_LEFT) . str_pad($points[2], 2, "0", STR_PAD_LEFT);
        //牌型  0未知(因别人弃牌而胜) 1高牌 2对子 3顺子 4同花 5同花顺 6三条
        if($points[0] == $points[2]){ //三条
            $card_type = "6";
        } else if($points[0] == $points[1] || $points[1] == $points[2]){ //对子
            $card_type = "2";
        } else if($points[0] == $points[2] + 2){ //顺子
            $card_type = ($suits[0] == $suits[1] && $suits[1] == $suits[2]) ? 5 : 3;
        } else if($points[0]==14&&$points[1]==3&&$points[2]==2){ //顺子123
            $card_type = ($suits[0] == $suits[1] && $suits[1] == $suits[2]) ? 5 : 3;
            $points_val_str = "010203";
        } else if($suits[0] == $suits[1] && $suits[1] == $suits[2]){  //同花
            $card_type = "4";
        } else {	//高牌
            $card_type = "1";
        }
        return $card_type.$points_val_str;
    }


    /**
     * 获取房间用户
     * @param $room_id
     * @param int $account_id
     * @return array|bool
     */
    public function getGamerInfo($room_id,$account_id=-1){
        $result = array();
        //获取房间所有用户
        $gamer_query = $this->queryRoomMembers($room_id, true);
        if(count($gamer_query) > 0) {
            foreach($gamer_query as $gamer_id=>$serial_num) {
                //获取玩家信息
                $account_query = $this->mysql()->from(WX_Account)->select("nickname,headimgurl")->where('account_id="'.$gamer_id.'"')->row();
                if(!is_array($account_query) || count($account_query) == 0 ) {
                    $this->logMessage('error', "function(getGamerInfo):account($gamer_id) not exist"." in file".__FILE__." on Line ".__LINE__);
                    return false;
                }
                $info['serial_num'] = $serial_num;
                $info['account_id'] = $gamer_id;
                $info['nickname'] = $account_query['nickname'];
                $info['headimgurl'] = $account_query['headimgurl'];
                //获取玩家当前积分
                $info['account_score'] = $this->queryRoomScore($room_id, $gamer_id);
                //获取玩家当前状态
                $info['account_status'] =  $this->queryAccountStatus($room_id, $gamer_id);
                $info['online_status'] = $this->queryOnlineStatus($room_id, $gamer_id);
                if($account_id == $gamer_id){
                    return $info;
                }

                $result[$gamer_id] = $info;

            }
        }

        return $result;
    }

    /**
     * 获取观战者
     * @param $room_id
     * @return array
     */
    public function getGuestInfo($room_id)
    {
        $result = array();
        //观战者列表
        $guests = $this->queryGuestList($room_id);
        if(count($guests)>0){
            $result = $this->mysql()->select("account_id,nickname,headimgurl")->from(WX_Account)->where('account_id in ('.implode(",", $guests).')')->query();
        }
        return $result;
    }

    //**************** REDIS **************************
    public function queryPlayingStatus($room_id, $account_id){
        $active_user =  $this->queryActiveUser($room_id);
        if($active_user != -1){
            $can_open = 0;
            $pk_user = array();
            if($this->queryPkChipConditon($room_id, $active_user)){
                $pk_user = $this->queryPkUser($room_id, $active_user);
                if(count($pk_user) > 0){
                    $can_open = 1;
                }
            }

            //通知:哪位正进行下注
            $noty_arr = array(
                'account_id' => $active_user,
                'playing_status' => Game::PlayingStatus_Betting,
                'limit_time'	 => $this->queryCountdown($room_id, Game::LimitTime_Betting),
                'can_open' => $can_open,
                'pk_user' => $pk_user ,
                'can_look' => $this->lookConditon($room_id, $active_user)
            );
            return $noty_arr;
        }
    }

    /**
     * 是否经过了第一轮下注，经过了才能比牌
     * @param $room_id
     * @param $account_id
     * @return bool
     */
    public function queryPkChipConditon($room_id, $account_id){
        $disable_pk_100 = $this->queryRoomSetting($room_id,Redis_Const::Room_Field_DisablePk100);
        if($disable_pk_100){
            if($this->queryPoolScore($room_id) < 100){
                return false;
            }
        }
        $chipKey = strtr(Redis_Const::Chip_Key, array("[roomid]"=>$room_id));
        $betScore = $this->redis()->hget($chipKey, $account_id);
        $default_score = $this->queryRoomSetting($room_id,Redis_Const::Room_Field_DefaultScore);
        if($betScore <= $default_score ){
            return false;
        }
        return true;
    }

    public function queryPkUser($room_id, $account_id){
        $playMemberKey = strtr(Redis_Const::PlayMember_Key, array("[roomid]"=>$room_id));
        $players = $this->redis()->lrange($playMemberKey, 0, -1);

        $other_players = array();
        foreach ($players as $player_id) {
            if($player_id != $account_id){
                $other_players[] = $player_id;
            }
        }
        $other_count = count($other_players) ;
        if($other_count == 1){
            $pk_user = $other_players;
        } else {
            $pk_user = array();
            foreach ($other_players as $player_id) {
                $status = $this->queryAccountStatus($room_id, $player_id);
                if($status == Game::AccountStatus_Visible){	//对方是看牌状态才能比牌
                    $pk_user[] = $player_id;
                }
            }
            if(count($pk_user) < $other_count ){ //有人闷牌
                $setting = $this->queryRoomSetting($room_id);
                $disable_pk_men=isset($setting[Redis_Const::Room_Field_DisablePkMen]) ?$setting[Redis_Const::Room_Field_DisablePkMen]:0;
                if($disable_pk_men){
                    $pk_user = array();
                }
            }
        }
        return $pk_user;
    }

    /**
     * 是否经过了第一轮下注，经过了才能看牌
     * @param $room_id
     * @param $account_id
     * @return bool
     */
    public function lookConditon($room_id, $account_id){
        $disable_look = $this->queryRoomSetting($room_id, Redis_Const::Room_Field_DisableLook);
        if($disable_look){
            $chipKey = strtr(Redis_Const::Chip_Key, array("[roomid]"=>$room_id));
            $betScore = $this->redis()->hget($chipKey, $account_id);
            $default_score = $this->queryRoomSetting($room_id, Redis_Const::Room_Field_DefaultScore);
            if($betScore <= $default_score ){
                return false;
            }
        }
        return true;
    }

    /**
     * 观战功能 (修改) 获取在房(入座)的人
     * @param $room_id
     * @return array
     */
    public function queryInRoomUser($room_id){
        $in_room_user_array = [];
        $room_members = $this->queryRoomMembers($room_id);
        $guests = $this->queryGuestList($room_id);
        $room_members = array_diff($room_members, $guests);

        foreach ($room_members as $account_id) {
            if($this->queryOnlineStatus($room_id, $account_id)){
                $in_room_user_array[] = $account_id;
            }
        }
        return $in_room_user_array;
    }



    


    

    //*************** GATEWAY ***********************
    


}